package org.hbgl.geoentity.admin.web.admin;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.hbgl.geoentity.admin.annotation.OperationLog;
import org.hbgl.geoentity.admin.annotation.RequiresPermissionsDesc;
import org.hbgl.geoentity.admin.aspect.OperationType;
import org.hbgl.geoentity.admin.shiro.UserType;
import org.hbgl.geoentity.admin.web.BaseController;
import org.hbgl.geoentity.core.util.JacksonUtil;
import org.hbgl.geoentity.core.util.ResponseUtil;
import org.hbgl.geoentity.db.domain.*;
import org.hbgl.geoentity.db.util.EnumFile;
import org.hbgl.geoentity.db.vo.CarouselVo;
import org.hbgl.geoentity.db.vo.CoVo;
import org.hbgl.geoentity.db.vo.ContentVo;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.stream.Collectors;

import static org.hbgl.geoentity.admin.util.ResponseCode.ADMIN_NAME_EXIST;

/**
 * 代码功能：内容管理
 * 开发日期：2022/4/26
 * 作者：蒋海仑
 * 联系方式：
 * 版本更迭说明：
 * 版权信息：河北广联信息技术有限公司
 */
@RestController
@RequestMapping("/admin/content")
@Validated
public class AdminContentController extends BaseController {

    //region 站点管理--内容管理

    /**
     * 获取内容列表
     */
    @RequiresPermissions("admin:content:list")
    @RequiresPermissionsDesc(menu = {"站点管理", "内容管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(@RequestParam(defaultValue = "-1") Integer columnId,
                       @RequestParam(defaultValue = "") String keywords,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit) {
        GeUser userCurrent = getCurrentAdminUser();
        List<ContentVo> contentList = contentService.selectContentList(columnId, keywords, page, limit);
        return ResponseUtil.okList(contentList);
    }

    /**
     * 添加内容
     */
    @RequiresPermissions("admin:content:create")
    @RequiresPermissionsDesc(menu = {"站点管理", "内容管理"}, button = "添加内容")
    @OperationLog(detail = "新建内容", operationType = OperationType.INSERT, userType = UserType.ADMIN)
    @PostMapping("/create")
    public Object create(@RequestBody GeContent geContent) {
        Integer columnId = geContent.getColumnId();
        String title = geContent.getTitle();
        String content = geContent.getContent();
        if (!ObjectUtils.allNotNull(
                columnId, title, content
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(title)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        List<GeContent> contentList = contentService.findByTitleAndColumnId(columnId, title);
        if (contentList != null && contentList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "该栏目已经存在【" + title + "】的内容");
        }
        geContent.setUserId(userCurrent.getId());
        contentService.insertContent(geContent);
        return ResponseUtil.ok();
    }

    /**
     * 根据内容ID查询内容信息
     *
     * @param id 内容ID
     */
    @RequiresPermissions("admin:content:detail")
    @RequiresPermissionsDesc(menu = {"站点管理", "内容管理"}, button = "详情")
    @OperationLog(detail = "查看内容详情", operationType = OperationType.SELECT, userType = UserType.ADMIN)
    @GetMapping("/detail")
    public Object detail(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();

        ContentVo contentVo = contentService.findContentById(id);
        if (contentVo == null) {
            return ResponseUtil.badArgumentValue();
        }

        return ResponseUtil.ok(contentVo);
    }

    /**
     * 删除内容
     *
     * @param id 内容id
     */
    @RequiresPermissions("admin:content:delete")
    @RequiresPermissionsDesc(menu = {"站点管理", "内容管理"}, button = "删除")
    @OperationLog(detail = "删除内容", operationType = OperationType.DELETE, userType = UserType.ADMIN)
    @GetMapping("/delete")
    public Object delete(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();
        contentService.deleteContentById(id);
        return ResponseUtil.ok();
    }

    /**
     * 编辑内容信息
     *
     * @param geContent 内容信息
     */
    @RequiresPermissions("admin:content:update")
    @RequiresPermissionsDesc(menu = {"站点管理", "内容管理"}, button = "编辑")
    @OperationLog(detail = "编辑内容信息", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/update")
    public Object update(@RequestBody GeContent geContent) {
        Integer id = geContent.getId();
        Integer columnId = geContent.getColumnId();
        String title = geContent.getTitle();
        String content = geContent.getContent();
        if (!ObjectUtils.allNotNull(
                id, columnId, title, content
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(title)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(content)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        ContentVo contentVo = contentService.findContentById(id);
        if (contentVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        List<GeContent> contentList = contentService.findByTitleAndColumnId(columnId, title);
        if (contentList != null && contentList.size() > 0) {
            for(GeContent item: contentList) {
                if(!item.getId().equals(geContent.getId())) {
                    return ResponseUtil.fail(ADMIN_NAME_EXIST, "该栏目已经存在【" + title + "】的内容");
                }
            }
        }

        if (contentService.updateContent(geContent) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 启用/禁用内容
     *
     * @param body { id : 内容ID, state : 状态 }
     */
    @RequiresPermissions("admin:content:state")
    @RequiresPermissionsDesc(menu = {"站点管理", "内容管理"}, button = "启用/禁用")
    @OperationLog(detail = "启用/禁用内容", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/state")
    public Object state(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        Integer state = JacksonUtil.parseInteger(body, "state");
        if (!ObjectUtils.allNotNull(
                id, state
        )) {
            return ResponseUtil.badArgument();
        }
        if (state != EnumFile.CommonState.Normal && state != EnumFile.CommonState.Disable) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        ContentVo contentVo = contentService.findContentById(id);
        if (contentVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        GeContent geContent = new GeContent();
        geContent.setId(id);
        geContent.setState(state);

        if (contentService.updateContent(geContent) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    //endregion

    //region 站点管理--站点设置

    /**
     * 获取站点管理
     */
    @RequiresPermissions("admin:site:see")
    @RequiresPermissionsDesc(menu = {"站点管理", "站点设置"}, button = "查看")
    @GetMapping("/see")
    public Object see() {
        GeUser userCurrent = getCurrentAdminUser();
        SiteSetting siteSetting = contentService.seeSiteSetting();
        if(siteSetting == null) {
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(siteSetting);
    }

    /**
     * 编辑站点管理
     */
    @RequiresPermissions("admin:site:seeupdate")
    @RequiresPermissionsDesc(menu = {"站点管理", "站点设置"}, button = "编辑")
    @PostMapping("/seeUpdate")
    public Object seeUpdate(@RequestBody SiteSetting siteSetting) {

        Integer id = siteSetting.getId();
        String siteName = siteSetting.getSiteName();
        String siteBanner = siteSetting.getSiteBanner();
        String siteLogo = siteSetting.getSiteLogo();
        if (!ObjectUtils.allNotNull(
                id, siteName, siteBanner, siteLogo
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(siteName)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(siteBanner)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(siteLogo)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        SiteSetting setting = contentService.seeSiteSetting();
        if (!setting.getId().equals(id)) {
            return ResponseUtil.badArgumentValue();
        }
        if (contentService.updateSiteSettingById(siteSetting) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    //endregion

    //region 站点管理--合作组织

    /**
     * 获取合作组织列表
     */
    @RequiresPermissions("admin:co:list")
    @RequiresPermissionsDesc(menu = {"站点管理", "合作组织管理"}, button = "查询")
    @GetMapping("/colist")
    public Object colist(@RequestParam(defaultValue = "") String keywords,
                         @RequestParam(defaultValue = "1") Integer page,
                         @RequestParam(defaultValue = "10") Integer limit) {
        GeUser userCurrent = getCurrentAdminUser();
        List<CoVo> coList = contentService.selectCoList(keywords, page, limit);
        return ResponseUtil.okList(coList);
    }

    /**
     * 添加合作组织
     */
    @RequiresPermissions("admin:co:create")
    @RequiresPermissionsDesc(menu = {"站点管理", "合作组织管理"}, button = "添加")
    @OperationLog(detail = "新建合作组织", operationType = OperationType.INSERT, userType = UserType.ADMIN)
    @PostMapping("/cocreate")
    public Object cocreate(@RequestBody GeCo geCo) {
        String title = geCo.getTitle();
        String coUrl = geCo.getCoUrl();
        String picUrl = geCo.getPicUrl();
        if (!ObjectUtils.allNotNull(
                title, coUrl, picUrl
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(title)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(coUrl)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(picUrl)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        List<GeCo> coList = contentService.findCoByTitle(title);
        if (coList != null && coList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "合作组织【" + title + "】已经存在");
        }
        geCo.setUserId(userCurrent.getId());
        contentService.insertCo(geCo);
        return ResponseUtil.ok();
    }

    /**
     * 根据合作组织ID查询合作组织信息
     *
     * @param id 合作组织ID
     */
    @RequiresPermissions("admin:co:detail")
    @RequiresPermissionsDesc(menu = {"站点管理", "合作组织管理"}, button = "详情")
    @OperationLog(detail = "查看内容详情", operationType = OperationType.SELECT, userType = UserType.ADMIN)
    @GetMapping("/codetail")
    public Object codetail(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();

        CoVo coVo = contentService.findCoById(id);
        if (coVo == null) {
            return ResponseUtil.badArgumentValue();
        }

        return ResponseUtil.ok(coVo);
    }

    /**
     * 删除合作组织
     *
     * @param id 合作组织id
     */
    @RequiresPermissions("admin:co:delete")
    @RequiresPermissionsDesc(menu = {"站点管理", "合作组织管理"}, button = "删除")
    @OperationLog(detail = "删除合作组织", operationType = OperationType.DELETE, userType = UserType.ADMIN)
    @GetMapping("/codelete")
    public Object codelete(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();
        contentService.deleteCoById(id);
        return ResponseUtil.ok();
    }

    /**
     * 编辑合作组织信息
     *
     * @param geCo 合作组织信息
     */
    @RequiresPermissions("admin:co:update")
    @RequiresPermissionsDesc(menu = {"站点管理", "合作组织管理"}, button = "编辑")
    @OperationLog(detail = "编辑合作组织信息", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/coupdate")
    public Object coupdate(@RequestBody GeCo geCo) {
        Integer id = geCo.getId();
        String coUrl = geCo.getCoUrl();
        String title = geCo.getTitle();
        String picUrl = geCo.getPicUrl();
        if (!ObjectUtils.allNotNull(
                id, coUrl, title, picUrl
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(title)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(coUrl)) {
            return ResponseUtil.badArgumentValue();
        }
//        if (StringUtils.isBlank(picUrl)) {
//            return ResponseUtil.badArgumentValue();
//        }

        GeUser userCurrent = getCurrentAdminUser();

        CoVo coVo = contentService.findCoById(id);
        if (coVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        List<GeCo> coList = contentService.findCoByTitle(title);
        if (coList != null && coList.size() > 0) {
            coList = coList.stream().filter(p->!p.getId().equals(id)).collect(Collectors.toList());
            if(coList != null && coList.size() > 0) {
                return ResponseUtil.fail(ADMIN_NAME_EXIST, "合作组织【" + title + "】已经存在");
            }
        }
        if (contentService.updateCo(geCo) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 启用/禁用合作组织
     *
     * @param body { id : 合作组织ID, state : 状态 }
     */
    @RequiresPermissions("admin:co:state")
    @RequiresPermissionsDesc(menu = {"站点管理", "合作组织管理"}, button = "启用/禁用")
    @OperationLog(detail = "启用/禁用合作组织", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/costate")
    public Object costate(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        Integer state = JacksonUtil.parseInteger(body, "state");
        if (!ObjectUtils.allNotNull(
                id, state
        )) {
            return ResponseUtil.badArgument();
        }
        if (state != EnumFile.CommonState.Normal && state != EnumFile.CommonState.Disable) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        CoVo coVo = contentService.findCoById(id);
        if (coVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        GeCo geCo = new GeCo();
        geCo.setId(id);
        geCo.setState(state);

        if (contentService.updateCo(geCo) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    //endregion

    //region 站点管理--轮播

    /**
     * 获取轮播列表
     */
    @RequiresPermissions("admin:carousel:list")
    @RequiresPermissionsDesc(menu = {"站点管理", "轮播管理"}, button = "查询")
    @GetMapping("/carousellist")
    public Object carousellist(@RequestParam(defaultValue = "") String keywords,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer limit) {
        GeUser userCurrent = getCurrentAdminUser();
        List<CarouselVo> coList = contentService.selectCarouselList(keywords, page, limit);
        return ResponseUtil.okList(coList);
    }

    /**
     * 添加轮播
     */
    @RequiresPermissions("admin:carousel:create")
    @RequiresPermissionsDesc(menu = {"站点管理", "轮播管理"}, button = "添加")
    @OperationLog(detail = "新建轮播", operationType = OperationType.INSERT, userType = UserType.ADMIN)
    @PostMapping("/carouselcreate")
    public Object carouselcreate(@RequestBody GeCarousel geCo) {
        String title = geCo.getTitle();
        String coUrl = geCo.getCoUrl();
        String picUrl = geCo.getPicUrl();
        if (!ObjectUtils.allNotNull(
                title, coUrl, picUrl
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(title)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(coUrl)) {
            return ResponseUtil.badArgumentValue();
        }
        if (StringUtils.isBlank(picUrl)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        List<GeCarousel> coList = contentService.findCarouselByTitle(title);
        if (coList != null && coList.size() > 0) {
            return ResponseUtil.fail(ADMIN_NAME_EXIST, "轮播【" + title + "】已经存在");
        }
        geCo.setUserId(userCurrent.getId());
        contentService.insertCarousel(geCo);
        return ResponseUtil.ok();
    }

    /**
     * 根据轮播ID查询轮播信息
     *
     * @param id 合作组织ID
     */
    @RequiresPermissions("admin:carousel:detail")
    @RequiresPermissionsDesc(menu = {"站点管理", "轮播管理"}, button = "详情")
    @OperationLog(detail = "查看轮播详情", operationType = OperationType.SELECT, userType = UserType.ADMIN)
    @GetMapping("/carouseldetail")
    public Object carouseldetail(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();

        CarouselVo coVo = contentService.findCarouselById(id);
        if (coVo == null) {
            return ResponseUtil.badArgumentValue();
        }

        return ResponseUtil.ok(coVo);
    }

    /**
     * 删除轮播
     *
     * @param id 轮播id
     */
    @RequiresPermissions("admin:carousel:delete")
    @RequiresPermissionsDesc(menu = {"站点管理", "轮播管理"}, button = "删除")
    @OperationLog(detail = "删除轮播", operationType = OperationType.DELETE, userType = UserType.ADMIN)
    @GetMapping("/carouseldelete")
    public Object carouseldelete(@NotNull Integer id) {
        GeUser userCurrent = getCurrentAdminUser();
        contentService.deleteCarouselById(id);
        return ResponseUtil.ok();
    }

    /**
     * 编辑轮播信息
     *
     * @param geCo 轮播信息
     */
    @RequiresPermissions("admin:carousel:update")
    @RequiresPermissionsDesc(menu = {"站点管理", "轮播管理"}, button = "编辑")
    @OperationLog(detail = "编辑轮播信息", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/carouselupdate")
    public Object carouselupdate(@RequestBody GeCarousel geCo) {
        Integer id = geCo.getId();
        String coUrl = geCo.getCoUrl();
        String title = geCo.getTitle();
        String picUrl = geCo.getPicUrl();
        if (!ObjectUtils.allNotNull(
                id, title, picUrl
        )) {
            return ResponseUtil.badArgument();
        }
        if (StringUtils.isBlank(title)) {
            return ResponseUtil.badArgumentValue();
        }
//        if (StringUtils.isBlank(coUrl)) {
//            return ResponseUtil.badArgumentValue();
//        }
        if (StringUtils.isBlank(picUrl)) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        CarouselVo coVo = contentService.findCarouselById(id);
        if (coVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        List<GeCarousel> coList = contentService.findCarouselByTitle(title);
        if (coList != null && coList.size() > 0) {
            coList = coList.stream().filter(p->!p.getId().equals(id)).collect(Collectors.toList());
            if(coList != null && coList.size() > 0) {
                return ResponseUtil.fail(ADMIN_NAME_EXIST, "轮播【" + title + "】已经存在");
            }
        }
        if (contentService.updateCarousel(geCo) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    /**
     * 启用/禁用轮播
     *
     * @param body { id : 轮播ID, state : 状态 }
     */
    @RequiresPermissions("admin:carousel:state")
    @RequiresPermissionsDesc(menu = {"站点管理", "轮播管理"}, button = "启用/禁用")
    @OperationLog(detail = "启用/禁用轮播", operationType = OperationType.UPDATE, userType = UserType.ADMIN)
    @PostMapping("/carouselstate")
    public Object carouselstate(@RequestBody String body) {
        Integer id = JacksonUtil.parseInteger(body, "id");
        Integer state = JacksonUtil.parseInteger(body, "state");
        if (!ObjectUtils.allNotNull(
                id, state
        )) {
            return ResponseUtil.badArgument();
        }
        if (state != EnumFile.CommonState.Normal && state != EnumFile.CommonState.Disable) {
            return ResponseUtil.badArgumentValue();
        }

        GeUser userCurrent = getCurrentAdminUser();

        CarouselVo coVo = contentService.findCarouselById(id);
        if (coVo == null) {
            return ResponseUtil.badArgumentValue();
        }
        GeCarousel geCo = new GeCarousel();
        geCo.setId(id);
        geCo.setState(state);

        if (contentService.updateCarousel(geCo) == 0) {
            return ResponseUtil.updatedDataFailed();
        }

        return ResponseUtil.ok();
    }

    //endregion

}
